from sqlalchemy import create_engine, text
from sqlalchemy.orm import sessionmaker, declarative_base

SQLALCHEMY_DATABASE_URL = "postgresql://postgres:1254088@localhost:5432/postgres"

engine = create_engine(SQLALCHEMY_DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()

#db = SessionLocal()
# 在现有代码后添加以下内容
# try:
#     # 尝试建立实际连接
#     with engine.connect() as conn:
#         result = conn.execute(text("SELECT 1"))
#         print("✅ 数据库连接成功！返回结果:", result.fetchone())
# except Exception as e:
#     print("❌ 数据库连接失败！错误信息:")
#     print(f"   → 类型: {type(e).__name__}")
#     print(f"   → 详情: {str(e)}")
# finally:
#     # 关闭所有连接
#     db.close()
#     engine.dispose()


# 定义依赖项
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()
